package com.wisdom.view;

import org.json.JSONException;
import org.json.JSONObject;

import com.hisun.phone.core.voice.Log4Util;
import com.wisdom.MainActivity;
import org.sipdroid.sipua.R;
import com.wisdom.VoiceApplication;
import com.wisdom.tools.CCPConfig;
import com.wisdom.tools.HttpUtil;
import com.wisdom.voip.VoiceHelper;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends Activity {
	public static final int WHAT_INIT_ERROR = 0x201C;
	EditText editPhone;
    EditText editPwd;
    private ProgressDialog mDialog;
    final String  logonUrl=CCPConfig.Mobile_BasicUrl+"/api/mobile/logon";
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		initResourceRefs();
	}
	public void goBack(View view){
		startActivity(new Intent(LoginActivity.this,WelcomeActivity.class));
	}
	public void resetPws(View view){
		startActivity(new Intent(LoginActivity.this,layout_resetpwd.class));
	}
	void showInitErrDialog(){
		new AlertDialog.Builder(this).setTitle(R.string.str_dialog_init_error_title)
				.setMessage(R.string.str_dialog_init_error_message)
				.setPositiveButton(R.string.dialog_btn,null).create().show();
	}
	private Handler helperHandler=new Handler(){
		 @Override
		 public void handleMessage(Message msg){
			 if(mDialog!=null){
				 mDialog.dismiss();
			 }
			 try{
				 if(msg.what==VoiceHelper.WHAT_ON_CONNECT){
					 if(!VoiceApplication.getInstance().isConnect()){
						 startAction();
						 VoiceApplication.getInstance().setConnect(true);
					 }
				 }else if(msg.what==VoiceHelper.WHAT_ON_DISCONNECT){
					 // do nothing
				 }else if(msg.what==WHAT_INIT_ERROR){
					 if(!VoiceApplication.getInstance().isConnect()){
						 showInitErrDialog();
					 }
				 }else{
					 Log4Util.d(VoiceHelper.WISDOMCALL_TAG,"Sorry , can't handle a message " + msg.what);
				 }
			 }catch(Exception e){
				 
			 }
			 super.handleMessage(msg);
		 }
	};
	public void logon(View view) throws JSONException{
				mDialog = new ProgressDialog(LoginActivity.this);
				mDialog.setMessage(getString(R.string.dialoglogon_message_text));
				mDialog.setCanceledOnTouchOutside(false);
				mDialog.show();
				String phone=editPhone.getText().toString();
				String pwd=editPwd.getText().toString();
				JSONObject object=new JSONObject("{Phone:\""+phone+"\",Password=\""+pwd+"\"}");
				JSONObject data=HttpUtil.post(logonUrl, object);
				if(data==null){
					Toast.makeText(getApplicationContext(), "未知错误！",Toast.LENGTH_SHORT).show();
					return;
				}
				if(data.getBoolean("success")){
					String accessToken=data.getString("AccessToken");
					String subAccount=data.getString("subAccount");
					String subToken=data.getString("subToken");
					String voipAccount=data.getString("voipAccount");
					String voipPwd=data.getString("voipPwd");
					String userId=data.getString("userId");
					String srcPhone=data.getString("srcPhone");
					String Balance=data.getString("balance");
					
					CCPConfig.setConfigProperties("accesstoken", accessToken);
					CCPConfig.setConfigProperties("sub_account",subAccount);
					CCPConfig.setConfigProperties("sub_token", subToken);
					CCPConfig.setConfigProperties("voip_account", voipAccount);
					CCPConfig.setConfigProperties("voip_password", voipPwd);
					CCPConfig.setConfigProperties("user_id", userId);
					CCPConfig.setConfigProperties("src_phone", srcPhone);
					CCPConfig.setConfigProperties("balance", Balance);
					CCPConfig.initProperties(getApplicationContext());
					startAction();
					/*VoiceHelper voiceHelper=VoiceApplication.getInstance().getVoiceHelper();
					if(voiceHelper!=null&&voiceHelper.getDevice()!=null){
						startAction();
					}else{
					//点击注册的时候初始化，以后是登陆的时候也要初始化
					
					new SDKInitAsyncTask().execute();
					}*/
				}else{
					Toast.makeText(getApplicationContext(), "登陆失败："+data.getString("message"),Toast.LENGTH_SHORT).show();
				}
	}
	void initResourceRefs(){
		editPhone=(EditText)findViewById(R.id.editText_phone);
		editPwd=(EditText)findViewById(R.id.editText_pwd);
	}
	class SDKInitAsyncTask extends AsyncTask<Void, Void, Void>{
		@Override
		protected Void doInBackground(Void... params) {
			VoiceApplication va= VoiceApplication.getInstance();
			va.initVoiceHelper(helperHandler);
			return null;
		}
		@Override
		protected void onPostExecute(Void result){
			super.onPostExecute(result);
			startAction();
		}
	}
private void startAction(){
		
		Intent intent=new Intent();
		intent.setClass(LoginActivity.this,HomeTabHostActivity.class);
		startActivity(intent);
	}

}

